require('dotenv').config();
const { NodeSSH } = require('node-ssh');
const path = require('path');

const ssh = new NodeSSH();

const config = {
  host: process.env.SERVER_HOST,
  username: process.env.SERVER_USER,
  password: process.env.SERVER_PASSWORD,
  tryKeyboard: true
};

const deployPath = process.env.DEPLOY_PATH;
const files = ['index.html', 'styles.css', 'script.js', 'removebg.html'];

async function deploy() {
  try {
    console.log('Connecting to server...');
    await ssh.connect(config);
    console.log('Connected successfully!');

    // 确保目录存在
    console.log('Creating directory...');
    await ssh.execCommand(`mkdir -p ${deployPath}`);

    // 上传文件
    console.log('Uploading files...');
    for (const file of files) {
      const localFile = path.join(__dirname, file);
      const remoteFile = `${deployPath}/${file}`;
      await ssh.putFile(localFile, remoteFile);
      console.log(`Uploaded ${file}`);
    }

    // 设置权限
    console.log('Setting permissions...');
    await ssh.execCommand(`chmod 755 -R ${deployPath}`);

    // 检测系统类型并安装 Apache
    console.log('Installing Apache...');
    const { stdout: osInfo } = await ssh.execCommand('cat /etc/os-release');
    console.log('OS Info:', osInfo);
    
    if (osInfo.toLowerCase().includes('id="centos"') || osInfo.toLowerCase().includes('id=centos') || osInfo.toLowerCase().includes('id="rhel"') || osInfo.toLowerCase().includes('id=rhel')) {
      console.log('Detected CentOS/RHEL system');
      // 安装 Apache
      const { stdout, stderr } = await ssh.execCommand('sudo dnf install -y httpd && sudo systemctl enable httpd && sudo systemctl start httpd');
      console.log('Installation output:', stdout);
      if (stderr) console.error('Installation errors:', stderr);

      // 配置 Apache
      console.log('Configuring Apache...');
      const apacheConfig = `
<VirtualHost *:80>
    DocumentRoot ${deployPath}
    
    <Directory ${deployPath}>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>`;

      await ssh.execCommand(`echo '${apacheConfig}' | sudo tee /etc/httpd/conf.d/removebg.conf`);
      
      // 重启 Apache
      console.log('Restarting Apache...');
      const { stdout: restartOut, stderr: restartErr } = await ssh.execCommand('sudo systemctl restart httpd');
      if (restartErr) {
        console.error('Apache restart errors:', restartErr);
        throw new Error('Apache restart failed');
      }

      // 检查 Apache 状态
      console.log('Checking Apache status...');
      const { stdout: statusOut } = await ssh.execCommand('sudo systemctl status httpd');
      console.log('Apache status:', statusOut);
    } else {
      console.log('Detected Ubuntu/Debian system');
      const { stdout, stderr } = await ssh.execCommand('sudo apt update && sudo apt install -y apache2');
      console.log('Installation output:', stdout);
      if (stderr) console.error('Installation errors:', stderr);

      // 配置 Apache
      console.log('Configuring Apache...');
      const apacheConfig = `
<VirtualHost *:80>
    DocumentRoot ${deployPath}
    
    <Directory ${deployPath}>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
</VirtualHost>`;

      await ssh.execCommand(`echo '${apacheConfig}' | sudo tee /etc/apache2/sites-available/removebg.conf`);
      await ssh.execCommand('sudo a2ensite removebg.conf');
      
      // 重启 Apache
      console.log('Restarting Apache...');
      const { stdout: restartOut, stderr: restartErr } = await ssh.execCommand('sudo systemctl restart apache2');
      if (restartErr) {
        console.error('Apache restart errors:', restartErr);
        throw new Error('Apache restart failed');
      }

      // 检查 Apache 状态
      console.log('Checking Apache status...');
      const { stdout: statusOut } = await ssh.execCommand('sudo systemctl status apache2');
      console.log('Apache status:', statusOut);
    }
    
    // 等待几秒确保安装完成
    console.log('Waiting for installation to complete...');
    await new Promise(resolve => setTimeout(resolve, 5000));
    
    // 检查服务器是否在运行
    console.log('Checking web server status...');
    const { stdout: processCheck } = await ssh.execCommand('ps aux | grep -E "httpd|apache2" | grep -v grep');
    console.log('Web server processes:', processCheck);
    
    if (!processCheck) {
      throw new Error('Web server is not running');
    }
    
    // 配置防火墙（如果需要）
    console.log('Configuring firewall...');
    await ssh.execCommand('sudo firewall-cmd --permanent --add-service=http || true');
    await ssh.execCommand('sudo firewall-cmd --reload || true');

    console.log('Deployment successful! ');
    console.log(`Your website is now available at: http://${process.env.SERVER_HOST}`);

  } catch (error) {
    console.error('Deployment failed:', error);
    console.error('Error details:', error.message);
  } finally {
    ssh.dispose();
  }
}

deploy();
